package com.qnbc.mystery.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.qnbc.mystery.domain.BoxInfo;
import com.qnbc.mystery.mapper.ProductSwiperImageMapper;
import com.qnbc.mystery.pojo.domain.FoodsProduct;
import com.qnbc.mystery.pojo.domain.ProductSwiperImage;
import com.qnbc.mystery.pojo.domain.User;
import com.qnbc.mystery.mapper.ProductMapper;
import com.qnbc.mystery.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.qnbc.mystery.mapper.CartMapper;
import com.qnbc.mystery.pojo.domain.Cart;
import com.qnbc.mystery.service.ICartService;

/**
 * 购物车Service业务层处理
 *
 * @author guzj
 * @date 2023-12-27
 */
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements ICartService {
    @Autowired
    private CartMapper cartMapper;


    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductSwiperImageMapper productSwiperImageMapper;


    @Autowired
    private BoxInfoServiceImpl boxInfoService;

    /**
     * 查询购物车
     *
     * @param id 购物车主键
     * @return 购物车
     */
    @Override
    public Cart selectCartById(Long id) {
        return cartMapper.selectCartById(id);
    }

    /**
     * 查询购物车列表
     *
     * @param cart 购物车
     * @return 购物车
     */
    @Override
    public List<Cart> selectCartList(Cart cart) {
        User currentUser = TokenUtils.getCurrentUser();
        String openId = String.valueOf(currentUser.getId());
        MPJLambdaWrapper<Cart> wrapper = new MPJLambdaWrapper<Cart>()
                .selectAll(Cart.class)//查询user表全部字段
                .selectAs(FoodsProduct::getName, Cart::getName)
                .selectAs(ProductSwiperImage::getName, Cart::getDetialName)
                .selectAs(ProductSwiperImage::getImage, Cart::getDetialImage)
                .selectAs(FoodsProduct::getPropic, Cart::getPropic)
                .select(FoodsProduct::getPrice).select(FoodsProduct::getDiscountNum)
                .leftJoin(FoodsProduct.class, FoodsProduct::getId, Cart::getProductId)
                .leftJoin(ProductSwiperImage.class, ProductSwiperImage::getId, Cart::getProductDetialId)
                .eq(Cart::getCreatedBy, openId);

        List<Cart> carts = cartMapper.selectList(wrapper);
        for (Cart cart1 : carts) {
            cart1.setPrice(cart1.getPrice());
        }
        return carts;
    }

    /**
     * 新增购物车
     *
     * @param cart 购物车
     * @return 结果
     */
    @Override
    public int insertCart(Cart cart) {
        User currentUser = TokenUtils.getCurrentUser();
        String userId = String.valueOf(currentUser.getId());
        cart.setUserId(userId);
        cart.setCreatedBy(userId);
        cart.setCreatedTime(new Date());
        MPJLambdaWrapper<Cart> wrapper = new MPJLambdaWrapper<Cart>()
                .selectAll(Cart.class)//查询user表全部字段
                .eq(Cart::getCreatedBy, userId);
        List<Cart> carts = cartMapper.selectList(wrapper);

        if (cart.getCartType() == 2) {
            BoxInfo boxInfo = boxInfoService.selectBoxInfoById(Long.valueOf(cart.getProductId()));
            if (null != boxInfo) {
                cart.setPrice(boxInfo.getBoxPrice());
                cart.setProductDetialId(String.valueOf(boxInfo.getId()));
                cart.setProductId(String.valueOf(boxInfo.getId()));
                cart.setCartType(boxInfo.getBoxType());
            }
        } else {
            ProductSwiperImage productSwiperImage = productSwiperImageMapper.selectProductSwiperImageById(Long.valueOf(cart.getProductId()));
            if (null != productSwiperImage) {
                cart.setPrice(productSwiperImage.getProPrice());
                cart.setProductDetialId(String.valueOf(productSwiperImage.getId()));
                cart.setProductId(String.valueOf(productSwiperImage.getProductid()));
                cart.setCartType(Integer.parseInt(productSwiperImage.getProType()));
            }
        }


        int i1 = 0;
        for (Cart cart1 : carts) {
            if (cart1.getProductId().equals(cart.getProductId())) {
                int i = cart1.getNum() + 1;
                cart1.setNum(i);
                i1 = cartMapper.updateById(cart1);
                return i1;
            }
        }
        i1 = cartMapper.insert(cart);
        return i1;
    }

    /**
     * 修改购物车
     *
     * @param cart 购物车
     * @return 结果
     */
    @Override
    public int updateCart(Cart cart) {
        return cartMapper.updateCart(cart);
    }

    /**
     * 批量删除购物车
     *
     * @param ids 需要删除的购物车主键
     * @return 结果
     */
    @Override
    public int deleteCartByIds(Long[] ids) {
        return cartMapper.deleteCartByIds(ids);
    }

    /**
     * 删除购物车信息
     *
     * @param id 购物车主键
     * @return 结果
     */
    @Override
    public int deleteCartById(Long id) {
        return cartMapper.deleteCartById(id);
    }

    @Override
    public Integer getTotalNum() {
        User currentUser = TokenUtils.getCurrentUser();
        String userId = String.valueOf(currentUser.getId());
        LambdaQueryWrapper<Cart> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Cart::getCreatedBy, userId);
        List<Cart> infos = cartMapper.selectList(queryWrapper);
        return infos.stream().mapToInt(Cart::getNum).sum();
    }

    @Override
    public BigDecimal getTotalPrice() {
        User currentUser = TokenUtils.getCurrentUser();
        String openid = String.valueOf(currentUser.getId());
        LambdaQueryWrapper<Cart> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Cart::getCreatedBy, openid);
        queryWrapper.isNull(Cart::getOrderNo);
        List<Cart> infos = cartMapper.selectList(queryWrapper);
        List<FoodsProduct> foodsProducts = new ArrayList<>();
        for (Cart info : infos) {
            if (info.getCartType() != 2) {
                FoodsProduct foodsProduct = productMapper.selectById(info.getProductId());
                if (info.getNum() > 1) {
                    foodsProduct.setPrice(foodsProduct.getPrice().multiply(new BigDecimal(info.getNum())));
                }
                foodsProducts.add(foodsProduct);
            }
        }

//计算 总金额
        BigDecimal discount = foodsProducts.stream().map(FoodsProduct::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
        return discount;
    }
}
